var userObj;

getUserList(1, 0, "");
getRoleNameList();

function getUserList(page, roleId, userName) {
//获取总页数
    const totalPage = $("#totalPage").html();
    //判断页码是否正确
    if (page < 1 || page > Number(totalPage)) {
        alert("请选择正确的操作");
    } else {
        loadUserList(page, roleId, userName);
    }
}
function deleteUser(userId) {
    if (confirm("确认删除？")) {
        //发送请求
        $.ajax({
            type: "DELETE",
            url: "user/" + userId,
            success(data) {
                if (data.code === 200) {
                    alert("删除成功")
                    location.href = "statics/jsp/user/userlist.jsp"
                } else {
                    alert(data.msg);
                }
            },
            error: function () {
                alert("系统异常11111")
            }
        })
    }
}


function updateUser(user) {

}
function erro() {
    alert("系统异常js")
}
function loadUserList(page, roleId, userName) {
    $.get("user/userList?currentPage=" + page + "&roleId=" + roleId + "&userName=" + userName, function (data) {
        if (data.code === 200) {
            var userList = $("#userList");
            //清空表单内容
            userList.empty();
            let sex = "女";
            for (let i = 0; i < data.data.list.length; i++) {
                var user = data.data.list[i];
                if (user.gender === 2) {
                    sex = "男"
                }
                // class="viewUser"id
                let str =
                    "<tr>" +
                    "<td><span>" + user.userCode + "</span></td>" +
                    "<td><span>" + user.userName + "</span></td>" +
                    "<td><span>" + sex + "</span></td>" +
                    "<td><span>" + datetime(new Date(user.birthday)) + "</span></td>" +
                    "<td><span>" + user.phone + "</span></td>" +
                    "<td><span>" + user.roleName + "</span></td>" +
                    "<td><span><a class='viewUser' href='statics/jsp/user/userCheck.jsp?userId="+user.id+"'><img src='statics/images/read.png' alt='查看' title='查看'/></a></span></td>"+
                    "<td><span><a class='viewUser' href='statics/jsp/user/userPut.jsp?userId=" + user.id + "'><img src='statics/images/xiugai.png' alt='修改' title='修改'/></a></a></span></td>"+
                    "<td><span><a class='viewUser' href='javascript:deleteUser("+user.id+")'><img src='statics/images/schu.png' alt='删除' title='删除'/></a></span></td>"+
                "</tr>"
                userList.append(str)
            }
            //设置总条数
            $("#total").html(data.data.total);
            //设置当前页
            $("#currentPage").html(data.data.pageNum);
            //设置总页码
            $("#totalPage").html(data.data.pages);
        } else {
            alert("出问题了。")
        }
    })
}

function getRoleNameList() {
    $.get("role/getRoleNameList", function (data) {
        if (data.code === 200) {
            var queryUserRole = $("#queryUserRole");
            for (let i = 0; i < data.data.length; i++) {
                var role = data.data[i];
                let str = "<option value='" + role.id + "'>" + role.roleName + "</option>";
                queryUserRole.append(str);
            }
        } else {
            alert(data.msg);
        }
    })

}

function datetime(date) {
    var date1 = new Date();
    return date1.getFullYear() - date.getFullYear()
}


//用户管理页面上点击删除按钮弹出删除框(userlist.jsp)
function deleteUr(obj) {
    $.ajax({
        type: "GET",
        url: path + "/jsp/user.do",
        data: {method: "deluser", uid: obj.attr("userid")},
        dataType: "json",
        success: function (data) {
            if (data.delResult == "true") {//删除成功：移除删除行
                cancleBtn();
                obj.parents("tr").remove();
            } else if (data.delResult == "false") {//删除失败
                //alert("对不起，删除用户【"+obj.attr("username")+"】失败");
                changeDLGContent("对不起，删除用户【" + obj.attr("username") + "】失败");
            } else if (data.delResult == "notexist") {
                //alert("对不起，用户【"+obj.attr("username")+"】不存在");
                changeDLGContent("对不起，用户【" + obj.attr("username") + "】不存在");
            }
        },
        error: function (data) {
            //alert("对不起，删除失败");
            changeDLGContent("对不起，删除失败");
        }
    });
}

function openYesOrNoDLG() {
    $('.zhezhao').css('display', 'block');
    $('#removeUse').fadeIn();
}

function cancleBtn() {
    $('.zhezhao').css('display', 'none');
    $('#removeUse').fadeOut();
}

function changeDLGContent(contentStr) {
    var p = $(".removeMain").find("p");
    p.html(contentStr);
}

$(function () {
    //通过jquery的class选择器（数组）
    //对每个class为viewUser的元素进行动作绑定（click）
    /**
     * bind、live、delegate
     * on
     */
    $(".viewUser").on("click", function () {
        //将被绑定的元素（a）转换成jquery对象，可以使用jquery方法
        var obj = $(this);
        window.location.href = path + "/jsp/user.do?method=view&uid=" + obj.attr("userid");
    });

    $(".modifyUser").on("click", function () {
        var obj = $(this);
        window.location.href = path + "/jsp/user.do?method=modify&uid=" + obj.attr("userid");
    });

    $('#no').click(function () {
        cancleBtn();
    });

    $('#yes').click(function () {
        deleteUser(userObj);
    });

    $(".deleteUser").on("click", function () {
        userObj = $(this);
        changeDLGContent("你确定要删除用户【" + userObj.attr("username") + "】吗？");
        openYesOrNoDLG();
    });

    /*$(".deleteUser").on("click",function(){
        var obj = $(this);
        if(confirm("你确定要删除用户【"+obj.attr("username")+"】吗？")){
            $.ajax({
                type:"GET",
                url:path+"/jsp/user.do",
                data:{method:"deluser",uid:obj.attr("userid")},
                dataType:"json",
                success:function(data){
                    if(data.delResult == "true"){//删除成功：移除删除行
                        alert("删除成功");
                        obj.parents("tr").remove();
                    }else if(data.delResult == "false"){//删除失败
                        alert("对不起，删除用户【"+obj.attr("username")+"】失败");
                    }else if(data.delResult == "notexist"){
                        alert("对不起，用户【"+obj.attr("username")+"】不存在");
                    }
                },
                error:function(data){
                    alert("对不起，删除失败");
                }
            });
        }
    });*/
});